package de.global42.clubapp.ejbs;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import de.global42.clubapp.model.Client;

/**
 * @author dominik
 *
 */
@Stateless
public class ClientRegistratorBean implements ClientRegistrator {
	
	private EntityManager entityManager;
	
	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public String register() {
		Client client = new Client();
		
		assignUniqueIdentifier(client);
		
		client.setRegisteredOn();
		client.setLastActivity();
		
		entityManager.persist(client);
		return client.getIdentifier();
	}

	/**
	 * 
	 * @param {@link Client} client whose identifier should be assigned
	 */
	private void assignUniqueIdentifier(Client client) {
		TypedQuery<Client> identifierQuery;
		do {
			client.setIdentifier();
			identifierQuery = entityManager.createQuery("SELECT c FROM Client c WHERE c.identifier = '" + client.getIdentifier() + "'", Client.class);
		}while(identifierQuery.getResultList().size() > 0);
	}
	
	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}
}
